<template>
  <a-row :gutter="24">
    <a-col :md="4" :sm="24">
      <div style="height: 100%;padding-top: 1.2vw;box-sizing: border-box;overflow: hidden;">
        <div class="deviceList">
          <div class="title">设备名称</div>
          <div class="list">
            <li
              v-for="(item, index) in deviceList"
              :key="item.id"
              @click="getDeviceId(item.id, index)"
              :class="{ 'active': currentDeviceIndex === index }">
              {{ item.deviceName }}
            </li>
          </div>
        </div>
        <div class="page">
          共{{ deviceList.length }}条数据
        </div>
      </div>
    </a-col>
    <a-col :md="4" :sm="24" style="margin-left: 1.5625vw;">
      <div style="height: 100%;padding-top: 1.2vw;box-sizing: border-box;overflow: hidden;">
        <div class="gatewayList">
          <div class="title">网关名称</div>
          <div class="list">
            <li
              v-for="(item, index) in gatewayList"
              :key="item.id"
              @click="getGatewayId(item.id, index)"
              :class="{ 'active': currentGatewayIndex === index }">
              {{ item.gatewayName }}
            </li>
          </div>
        </div>
        <div class="page">
          共{{ gatewayList.length }}条数据
        </div>
      </div>
    </a-col>
    <a-col :md="14" :sm="24">
      <div style="width: 100%;height: 100%;display: flex;flex-direction: column;">
        <div class="tdList">
          <div
            class="td"
            v-for="(item, index) in channelList"
            :key="item.id"
            :class="getstatus(item, index)"
            @click="handleChannelClick(item, index)"
          >#{{ item.channel }} {{ getstatusText(item) }}
          </div>
        </div>
        <div class="sb-pic" style="flex: 1;">
          <!-- <img src="../../../assets/img/account.png" alt="" style="width: 100%;"> -->
          <div class="markers">
            <image-markers-view1
              :markers="markers"
              :imageData="imgName"
              :editorMode="true"
              :imgStatus="imgStatus"
              @onEditorTouch="onEditorTouch"
              @onMouseUp="onMouseUp"
              @imgError="imgError"
            />
          </div>
          <div class="sb-pic-tab" v-if="isTab">
            <div class="item" :class="{'active': currentFace === 'front'}" @click="handleTab('front')">设备正面</div>
            <div class="item" :class="{'active': currentFace === 'back'}" @click="handleTab('back')" v-if="isBack">设备反面</div>
          </div>
        </div>
      </div>
    </a-col>
  </a-row>
</template>

<script>
  import { STable } from '@/components'
  import { deviceList, detail, pageDecive } from '@/api/modular/main/bizdevice/bizDeviceManage'
  import addForm from '../bizstation/addForm'
  import editForm from '../bizstation/editForm'
  // import ARow from 'ant-design-vue/es/grid/Row'
  import { gatewayList, pageGataway } from '@/api/modular/main/bizgateway/bizGatewayManage'
  import ImageMarkersView1 from '@/components/ImageMarkersView/ImageMarkersView1'
  import {
    listChannel,
    unbinding,
    mark,
    queryChannelBindingInfo
  } from '@/api/modular/main/bizgatewaychannel/bizGatewayChannelManage'

  export default {
    components: {
      // ARow,
      STable,
      addForm,
      editForm,
      ImageMarkersView1
    },
    props: {
      stationId: {
        type: Number,
        require: false
      },
      stationName: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        fileUrl: window.CONST.VUE_APP_API_BASE_FILE_URL,
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '录音时段',
            dataIndex: 'timeSchedule',
            scopedSlots: { customRender: 'timeSchedule' }
          },
          {
            title: '网关名称',
            dataIndex: 'gatewayName',
            width: 100
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: 150,
            scopedSlots: { customRender: 'action' },
            align: 'center'
          }
        ],
        form: this.$form.createForm(this),
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        deciveColumns: [
          {
            title: '设备名称',
            dataIndex: 'deviceName',
            ellipsis: true
          }
        ],
        deciveQueryParam: {},
        loadDeciveData: parameter => {
          return pageDecive(Object.assign(parameter, this.deciveQueryParam)).then((res) => {
            return res.data
          })
        },
        gatewayColumns: [
          {
            title: '网关名称',
            dataIndex: 'gatewayName',
            ellipsis: true
          }
        ],
        // 设备列表
        deviceList: [],
        currentDeviceIndex: -1,
        // 网关列表
        gatewayList: [],
        currentGatewayIndex: -1,
        gatewayQueryParam: {},
        loadGatewayData: parameter => {
          return pageGataway(Object.assign(parameter, this.gatewayQueryParam)).then((res) => {
            return res.data
          })
        },
        selectedDeviceRowKeys: [],
        selectedGatewayRowKeys: [],

        deviceId: 0,
        deviceName: '',
        // 当前选中的设备图片路径
        imgName: '',
        // 网关id
        gatewayId: 0,
        // 通道列表
        channelList: [],
        routers: [],
        markers: [], // 已添加的点,
        routeItem: {},
        routerIndex: -1,
        markerIndex: 0,
        imgStatus: 'none',
        // 设备图片当前面: front正面，back反面，默认正面
        currentFace: '',
        // 选择设备前不显示正反面tab
        isTab: false,
        // 是否显示设备反面tab
        isBack: false
      }
    },

    created () {
      this.getDeviceList()
      this.getGatewayList()
    },
    computed: {
      getstatus () {
        return (item, index) => {
          let status = ''
          if (item.deviceId === 0) {
            status = 'kbd'
          } else if (item.deviceId !== 0 && item.deviceId !== this.deviceId) {
            status = 'kjb'
          } else if (item.deviceId === this.deviceId) {
            if (this.routerIndex === index) {
              status = 'ybd active'
            } else {
              status = 'ybd'
            }
          }
          return status
        }
      },
      getstatusText () {
        return (item) => {
          let statusText = ''
          if (item.deviceId === 0) {
            statusText = '可绑定'
          } else if (item.deviceId !== 0 && item.deviceId !== this.deviceId) {
            statusText = '可解绑'
          } else if (item.deviceId === this.deviceId) {
            statusText = '已绑定'
          }
          return statusText
        }
      }
    },
    methods: {
      handleTab (face) {
        detail({
          id: this.deviceId
        }).then(res => {
          // 正反面记录
          this.currentFace = face
          // 通过currentFace来确定图片的路径值
          if (this.currentFace === 'front') {
            this.imgName = this.fileUrl + res.data.fileName
          } else if (this.currentFace === 'back') {
            this.imgName = this.fileUrl + res.data.backFileName
          }
          this.routerIndex = -1
          this.markerIndex = 0
          this.markers = []
          this.getChannelList(this.gatewayId)
        })
      },
      imgError () {
        this.imgStatus = 'error'
      },
      // 获取设备列表
      getDeviceList () {
        deviceList({ stationId: this.stationId }).then(res => {
          this.deviceList = res.data
        })
      },
      getDeviceId (id, index) {
        this.deviceId = id
        this.deviceName = this.deviceList[index].deviceName
        this.currentDeviceIndex = index
        this.imgStatus = 'right'
        this.isTab = true
        // 点击设备列表时默认选中设备正面
        this.currentFace = 'front'
        this.routerIndex = -1
        this.markerIndex = 0
        this.markers = []
        this.isBack = false
        detail({
          id: id
        }).then((res) => {
          this.imgName = this.fileUrl + res.data.fileName
          // 如果设备有反面图片则显示反面tab
          if (res.data.backFileName) {
            this.isBack = true
          }
        })
        // 选取后更新通道数据
        if (this.gatewayId) {
          this.getGatewayId(this.gatewayId, this.currentGatewayIndex)
        }
      },
      // 获取网关列表
      getGatewayList () {
        gatewayList({ stationId: this.stationId }).then(res => {
          this.gatewayList = res.data
        })
      },
      getGatewayId (id, index) {
        // 如果还没有选择设备则提示先选择设备
        if (!this.deviceId) {
          this.$message.error('请选择要绑定的设备')
          return
        }
        this.gatewayId = id
        this.currentGatewayIndex = index
        // 重置设备图片为正面
        this.currentFace = 'front'
        this.routerIndex = -1
        this.markerIndex = 0
        this.markers = []
        this.getChannelList(this.gatewayId)
      },
      // 获取通道列表
      getChannelList (id, index) {
        listChannel({
          gatewayId: id
        }).then((res) => {
          this.channelList = res.data
          this.filterMarkers()
          // 计算routerIndex
          if (this.markers.length > 0) {
            if (index) {
              this.routerIndex = index
            } else {
              for (let i = 0; i < this.channelList.length; i++) {
                if (this.channelList[i].id === this.markers[this.markerIndex].id) {
                  this.routerIndex = i
                  break
                }
              }
            }
          }
          // 默认选中第一个
          if (this.markers.length > 0) {
            this.getChannelInfo(this.channelList[this.routerIndex], this.markerIndex)
          }
        })
      },
      // 处理解绑操作
      handleUnbinding (item, index) {
        const param = { id: item.id }
        queryChannelBindingInfo(param).then(res => {
          if (res.success) {
            this.$confirm({
              title: `该通道已绑定${this.stationName}的${this.deviceName}，是否解绑并重新绑定至本设备`,
              content: '',
              okText: '确定',
              cancelText: '取消',
              onOk: () => {
                // 解绑
                unbinding(param).then((res) => {
                  if (res.success) {
                    // this.$message.success('解绑成功')
                    this.handleBinding(item, index)
                    // this.getChannelList(this.gatewayId)
                  } else {
                    this.$message.error(res.message)
                  }
                })
              }
            })
          }
        })
      },
      // 处理绑定操作
      handleBinding (item, index) {
        const positionType = this.currentFace === 'front' ? '0' : '1'
        const params = {
          deviceId: this.deviceId,
          gatewayId: this.gatewayId,
          id: item.id,
          xposion: item.xposion,
          yposion: item.yposion,
          positionType: positionType
        }
        mark(params).then(res => {
          if (res.success) {
            this.$message.success('綁定成功')
            for (let j = 0; j < this.markers.length; j++) {
              if (this.channelList[index].id === this.markers[j].id) {
                this.markerIndex = j
                break
              }
            }
            this.getChannelList(this.gatewayId, index)
            // this.routerIndex = index
          } else {
            this.$message.error(res.message)
          }
        })
      },

      handleChannelClick (item, index) {
        if (item.deviceId !== 0 && item.deviceId !== this.deviceId) {
          this.handleUnbinding(item, index)
        } else if (item.deviceId === 0) {
          this.handleBinding(item, index)
        } else {
          // 切换tab状态
          this.currentFace = item.positionType === '0' ? 'front' : 'back'
          // 切换设备图正反面
          detail({
            id: this.deviceId
          }).then((res) => {
            if (this.currentFace === 'front') {
              this.imgName = this.fileUrl + res.data.fileName
            } else if (this.currentFace === 'back') {
              this.imgName = this.fileUrl + res.data.backFileName
            }
            // 计算当前活跃marker的索引 -- markerIndex
            if (this.markers.length > 0) {
              for (let j = 0; j < this.markers.length; j++) {
                if (this.channelList[index].id === this.markers[j].id) {
                  this.markerIndex = j
                  break
                }
              }
            }
            this.getChannelList(this.gatewayId, index)
          })
        }
      },
      filterMarkers () {
        const markers0 = []
        const markers1 = []
        // for循环this.channelList筛选当前设备绑定的通道
        for (let i = 0; i < this.channelList.length; i++) {
          if (this.channelList[i].deviceId === this.deviceId) {
            let param = {
              x: this.channelList[i].xposion + '%',
              y: this.channelList[i].yposion + '%',
              id: this.channelList[i].id,
              channel: this.channelList[i].channel,
              status: '',
              positionType: this.channelList[i].positionType
            }
            // 通过channelTypeCode来区分不同类型的通道
            if (this.channelList[i].channelTypeCode.trim() === 'ZKHY-AWG-001') {
              param = Object.assign(param, { url: 'mic-sonic-source' })
            } else {
              param = Object.assign(param, { url: 'mic-offline' })
            }
            // 通过positionType来区分正反面的通道
            if (this.channelList[i].positionType === '0') {
              markers0.push(param)
            } else if (this.channelList[i].positionType === '1') {
              markers1.push(param)
            }
          }
        }
        // 通过currentFace来确定现在需要的时正面markers还是反面markers
        if (this.currentFace === 'front') {
          this.markers = markers0
        } else if (this.currentFace === 'back') {
          this.markers = markers1
        }
        console.log(this.markers)
      },
      // 对获取到的通道信息做处理
      getChannelInfo (item, index) {
        // 遍历所有的marker设为离线
        this.markers.forEach(value => {
          value.status = ''
        })
        // 找到选择的marker将其status改成selected
        this.markers.find(
          value => {
            if (value.id === item.id) {
              // this.markers[index].url = 'mic-normal'
              this.markers[index].status = 'selected'
            }
          }
        )
      },
      onEditorTouch ({ x, y }) {
        const routeItem = this.channelList[this.routerIndex]
        if (this.markers.length) {
          this.markers.forEach((item, index) => {
            if (item.id === routeItem.id) {
              this.markerIndex = index
            }
          })
          this.markers[this.markerIndex].x = x
          this.markers[this.markerIndex].y = y
        }
      },
      onMouseUp () {
        this.markers[this.markerIndex] && this.editChannelPosion(this.markers[this.markerIndex])
      },
      editChannelPosion (routeItem) {
        const positionType = this.currentFace === 'front' ? '0' : '1'
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            values.deviceId = this.deviceId
            values.gatewayId = this.gatewayId
            values.id = routeItem.id
            values.xposion = routeItem.x.replace('%', '')
            values.yposion = routeItem.y.replace('%', '')
            values.positionType = positionType
            mark(values).then((res) => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success('编辑成功')
                this.getChannelList(this.gatewayId)
              } else {
                this.$message.info('编辑失败：' + res.message)
              }
            })
          }
        })
      }
    }
  }
</script>

<style  lang="less" scoped>
  @import '../~@/assets/css/list.less';

  .ant-col-md-18, .ant-col-md-19, .ant-col-md-17, .ant-col-md-16, .ant-col-md-14 {
    height: 60vh !important;
  }

  .ant-col-md-5, .ant-col-md-4, .ant-col-md-3 {
    height: 60vh !important;
  }

  .ant-card {
    height: 100% !important;

    .ant-card-body {
      height: 100% !important;
    }
  }

  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }

  .tdList {
    // overflow-x:scroll ;/*只是x方向*/

    display: flex;
    // align-items: center;
    margin-bottom: 2vw;
    // overflow: hidden;
    height: 40px;
    width: 100%;

    .td {
      padding: 0 5px;
      height:2vw;
      font-size: 12px;
      // text-align: center;
      line-height: 1.8vw;
      margin: 0 10px;
    }

    .td.ybd {
      border: 1px solid #2097F2;
      background-color: #2097F2;
    }

    .td.ybd.active {
      border: 1px solid #fff;
      background: #2097F2 url("../../../assets/img/icon-channel-active.png") no-repeat top right;
    }

    .td.kjb {
      border: 1px solid #626262;
      background-color: #626262;
    }

    .td.kbd {
      border: 1px solid #626262;
      background-color: #0FC44F;
    }
  }

  .sb-pic {
    position: relative;
    height: 50vh;
    padding-right: calc(3.28125vw + 6%);
    box-sizing: border-box;
    .sb-pic-tab{
      position: absolute;
      right: 2%;
      .item{
        width: 3.28125vw;
        height: 8.489583vw;
        background: url("../../../assets/img/bg-sbTab.png") center center no-repeat;
        background-size: 100% 100%;
        margin-bottom: 0.78125vw;
        color: #138894;
        font-size: 1.25vw;
        padding: 1.6666667vw 0.52083vw;
        text-align: center;
        line-height: 1;
      }
      .item.active{
        color: #18F7FF;
        background: url("../../../assets/img/bg-sbTab-active.png") center center no-repeat;
        background-size: 100% 100%;
      }
    }
  }

  .markers {
    position: absolute;
    top: 0;
    right: calc(3.28125vw + 6%);
    bottom: 0;
    left: 0;
  }

  .deviceList, .gatewayList {
    height: 80%;
    overflow: hidden;
    overflow-y: auto;
  }

  .page {
    height: 20%;
    font-size: 16px;
    padding-top: 16px;
    box-sizing: border-box;
  }

  .deviceList li, .gatewayList li {
    width: 100%;
    text-align: left;
    height: 2vw;
    line-height: 2vw;
    padding-left: 10px;
    box-sizing: border-box;
  }

  .deviceList li.active, .gatewayList li.active {
    background-color: #5e9ad6;
  }

  .deviceList .title, .gatewayList .title {
    line-height: 2vw;
    background-color: #104E5C;
  }
</style>
